<template>
  <Category :sceen="sceen"></Category>
  <el-card style="margin-top: 10px">
    <div v-show="sceen == 0">
      <el-button
        type="primary"
        icon="Plus"
        @click="addAttr"
        :disabled="!categoryStore.c3Id"
      >
        添加平台属性
      </el-button>
      <el-table
        :data="tableData"
        border
        style="margin: 10px 0px; width: 100%"
        v-if="tableData.length > 0"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="attrName" label="属性名称" width="120" />
        <el-table-column label="属性值名称">
          <template #="{ row }">
            <el-tag
              v-for="item in row.attrValueList"
              :key="item.id"
              style="margin: 5px"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="120">
          <template #="{ row, index }">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="udateAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定删除${row.attrName}`"
              width="250px"
              icon="delete"
              @confirm="removeAttr(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="sceen == 1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        icon="Plus"
        :disabled="!attrParams.attrName"
        @click="addAttrValue"
      >
        添加属性值
      </el-button>
      <el-button type="primary">取消</el-button>
      <el-table
        :data="attrParams.attrValueList"
        border
        style="margin: 10px 0px; width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="attrName" label="属性值名称">
          <template #="{ row, $index }">
            <el-input
              placeholder="请输入属性值名称"
              :ref="(vc: any) => (inputArr[$index] = vc)"
              size="small"
              v-model="row.valueName"
              v-if="row.flag"
              @blur="toLook(row, $index)"
            ></el-input>
            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="delete"
              @click="attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="save"
        :disabled="!attrParams.attrValueList.length > 0"
      >
        保存
      </el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { reactive, ref, watch, nextTick, onBeforeUnmount } from 'vue'
import Category from '@/components/Category/index.vue'
import useCategoryStore from '@/store/modules/category'
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqRemoveAttr,
} from '@/api/product/attr/index'
import { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
let categoryStore = useCategoryStore()
const tableData = ref<Attr[]>([])
const sceen = ref<number>(0)
const inputArr = ref<any>([])

const getList = async () => {
  const { c1Id, c3Id, c2Id } = categoryStore
  const res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  tableData.value = res.data
}
// 监听三级分类的id刷新列表
watch(
  () => categoryStore.c3Id,
  () => {
    tableData.value = []
    if (!categoryStore.c3Id) return
    getList()
  },
)

let attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})
// 添加平台属性
const addAttr = () => {
  sceen.value = 1
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
  })
}
// 添加属性值
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
// 编辑
const udateAttr = (row: Attr) => {
  sceen.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 删除
const removeAttr = async (id: number) => {
  const res: any = await reqRemoveAttr(id)
  if ((res.code = 200)) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getList()
  } else {
    ElMessage({
      type: 'error',
      message: res.data,
    })
  }
}
// 取消按钮
const cancel = () => {
  sceen.value = 0
}
// 保存
const save = async () => {
  let flag = false
  attrParams.attrValueList.forEach((item) => {
    if (!item.valueName) {
      flag = true
    }
  })
  if (flag) {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 添加或者修改数据
  const res = await reqAddOrUpdateAttr(attrParams)
  if ((res.code = 200)) {
    sceen.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    getList()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
const toLook = (row: AttrValue, $index: number) => {
  // 不能为空
  if (row.valueName.trim() == '') {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 不能重复
  let repeat = attrParams.attrValueList.find((item) => {
    if (item !== row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  row.flag = false
}
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

// 路由组件销毁的时候，清除子组件仓库的数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>
<style scoped lang="scss"></style>
